import { authMiddleware } from '@/lib/api';
import { queryOauthClientByClientId, queryPath } from '@/services/api';
import { cookies } from 'next/headers';
import ResetPage from '@/app/[locale]/reset/reset';
import OauthAuthPage from '@/app/[locale]/oauth/auth/auth';
import type { IOauthClient, IPath } from '@/interfaces';
import { notFound, redirect } from 'next/navigation';
import { createError, getMetadata } from '@/lib/tool';
import { nanoid } from 'nanoid';
import type { Metadata as MetadataNext } from 'next';
import { getTranslator } from 'next-intl/server';
import { getTranslatedFields } from '@/lib/dictionaries';

export async function generateMetadata({
  params: { locale },
}: {
  params: {
    locale: string;
  };
}): Promise<MetadataNext> {
  const t = await getTranslator(locale);
  return getMetadata({ title: t('oauthPage.openAuthClient') });
}

async function getData(searchParams: {
  clientId: string;
  responseType: string;
  redirectUri: string;
  scope: string;
  state: string;
}) {
  try {
    const token = authMiddleware(cookies());
    const req1 = queryPath({
      baseURL: process.env.APP_API_SERVER,
      token,
      query: {
        name: '/',
      },
    });
    const req2 = queryOauthClientByClientId({
      baseURL: process.env.APP_API_SERVER,
      token,
      id: searchParams.clientId,
    });

    const responses = await Promise.all([req1, req2]);
    const resp1 = await ((await responses[0]) as Response).json();
    const resp2 = await ((await responses[1]) as Response).json();

    return {
      isSuccess: true,
      isError: false,
      data: {
        path: resp1.data as IPath,
        client: resp2.data as IOauthClient,
        queryParams: searchParams,
      },
    };
  } catch (e: any) {
    return {
      isSuccess: false,
      isError: true,
      error: e,
    };
  }
}

export default async function Page({
  params: { locale },
  searchParams,
}: {
  params: { locale: string };
  searchParams: {
    response_type: string;
    responseType: string;
    client_id: string;
    clientId: string;
    redirect_uri: string;
    redirectUri: string;
    scope: string;
    state?: string;
    ['client-id']: string;
    ['response-type']: string;
    ['redirect-uri']: string;
  };
}) {
  const clientId =
    searchParams.client_id ??
    searchParams.clientId ??
    searchParams['client-id'];
  const responseType =
    searchParams.response_type ??
    searchParams.responseType ??
    searchParams['response-type'];
  const redirectUri =
    searchParams.redirect_uri ??
    searchParams.redirectUri ??
    searchParams['redirect-uri'];
  const scope = searchParams.scope;
  const state = searchParams.state ?? nanoid();

  if (!clientId || !responseType || !redirectUri || !scope) {
    notFound();
  }

  const data = await getData({
    clientId,
    responseType,
    redirectUri,
    scope,
    state,
  });
  if (data.isError) {
    return <ResetPage error={createError(data.error)} />;
  }

  const source = data.data!;
  const translatedFields = await getTranslatedFields(locale, 'oauthPage');

  if (!source.path.user) {
    redirect(`/login?${new URLSearchParams(searchParams)}`);
  }

  return <OauthAuthPage source={source} translatedFields={translatedFields} />;
}
